//
//  Utility.m
//  AppFrameWork
//
//  Created by Le Anh Tai on 7/21/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "Utility.h"
#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>
#import "MBProgressHUD.h"
#import "Global.h"

@implementation Utility

+ (CGFloat)estimateTimeWithDis:(CGFloat) dis andVelocity:(CGFloat) vel
{
    CGFloat time = (dis / vel*1.5);
    return time > DEFAULT_SLOWEST_SPEED_TIME? DEFAULT_SLOWEST_SPEED_TIME:time;
}

+ (NSString*)stringCurrencyForInteger:(NSInteger)value
{
    NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
    NSNumber *number   = [NSNumber numberWithFloat:value];
    NSString *result;
    
    [fmt setFormatterBehavior: NSNumberFormatterBehaviorDefault];
    [fmt setCurrencySymbol: @""];
    [fmt setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"vi"]];
    [fmt setNumberStyle: NSNumberFormatterDecimalStyle];
    
    result = [fmt stringFromNumber:number];
    return result;
}

+ (void)createTwoTextStyleInSingleUILabel: (UILabel *) myLabel firstText:(NSString*)firstText secondText:(NSString*)secondText
{
    NSLog(@"Two text style");
    NSString *wholeText = [NSString stringWithFormat:@"%@%@",firstText,secondText];
    
    CATextLayer *myLabelTextLayer;
    /* Create the text layer on demand */
    if (!myLabelTextLayer) {
        myLabelTextLayer = [[CATextLayer alloc] init];
        myLabelTextLayer.backgroundColor = [UIColor clearColor].CGColor;
        myLabelTextLayer.wrapped = NO;
        CALayer *layer = myLabel.layer; //assign layer to your UILabel
        //        myLabelTextLayer.frame = CGRectMake((layer.bounds.size.width-myLabel.width)/2 + 10, (layer.bounds.size.height-21)/2, myLabel.width, myLabel.height);
        myLabelTextLayer.frame = CGRectMake(4, 4, myLabel.width, myLabel.height);
        myLabelTextLayer.contentsScale = [[UIScreen mainScreen] scale];
        myLabelTextLayer.alignmentMode = kCAAlignmentCenter;
        [layer addSublayer:myLabelTextLayer];
    }
    /* Create the attributes (for the attributed string) */
    // customizing first string
    CGFloat fontSize = 15;
    UIFont *boldFont = FONT_HELVETICANEUE_BOLD(fontSize);
    CTFontRef ctBoldFont = CTFontCreateWithName((__bridge CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
    CGColorRef cgColor = COLOR(246, 197, 70, 1).CGColor;
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                (__bridge id)ctBoldFont, (id)kCTFontAttributeName,
                                cgColor, (id)kCTForegroundColorAttributeName, nil];
    CFRelease(ctBoldFont);
    // customizing second string
    UIFont *font = FONT_HELVETICANEUE(11);
    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
    CGColorRef cgSubColor = cgColor;
    NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)ctFont, (id)kCTFontAttributeName,cgSubColor, (id)kCTForegroundColorAttributeName, nil];
    CFRelease(ctFont);
    /* Create the attributed string (text + attributes) */
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:wholeText attributes:attributes];
    float lengthOfSecondString = 1;//secondText.length - 1; // length of second string including blank space inbetween text, space in front , space after text.. Be careful, your  app may crash here if length is beyond the second text length (lengthOfSecondString = text length + blank spaces)
    [attrStr addAttributes:subAttributes range:NSMakeRange(firstText.length, lengthOfSecondString)];
    // you can add another subattribute in the similar way as above , if you want change the third textstring style
    /* Set the attributes string in the text layer :) */
    myLabelTextLayer.string = attrStr;
    myLabelTextLayer.opacity = 1.0; //to remove blurr effect
    
}

+ (void) showLoading:(UIView*)vw withMsg:(NSString*)msg
{
    [MBProgressHUD hideAllHUDsForView:vw animated:NO];
    
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:vw animated:YES];
    hud.labelText = msg;
    hud.removeFromSuperViewOnHide = YES;
    hud.mode = MBProgressHUDModeIndeterminate;
    
    vw.userInteractionEnabled = NO;
}

+ (void) hideLoading:(UIView*)vw
{
    vw.userInteractionEnabled = YES;
    
    [MBProgressHUD hideHUDForView:vw animated:YES];
}

+ (void)showInfoMsg:(NSString*)msg inView:(UIView*)vw
{
    [MBProgressHUD hideAllHUDsForView:vw animated:NO];
    
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:vw animated:YES];
    
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = @"";
    hud.detailsLabelText = msg;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [MBProgressHUD hideHUDForView:vw animated:YES];
    });
}

+ (NSString*)makeChangedString:(CGFloat)value
                      preValue:(CGFloat)preValue
               ignoreZeroValue:(BOOL)ignoreZeroValue
          changedPerInDiffLine:(BOOL)changedPerInDiffLine
{
    if (value == .0f)
    {
        return @"";
    }
    
    if (preValue == .0f)
    {
        return DEFAULT_EMPTY_OR_ZERO_TEXT;
    }
    
    float diff = value - preValue;
    
    if (ignoreZeroValue && diff == .0f)
    {
        return DEFAULT_EMPTY_OR_ZERO_TEXT;
    }
    
    NSString *sign = @"+";
    
    if (diff < 0)
    {
        sign = @"";
    }
    
    if (changedPerInDiffLine)
    {
        return [NSString stringWithFormat:FORMAT_CHANGED_LABEL_2_LINES,
                sign,
                [self stringCurrencyForInteger:(int)diff],
                fabs(diff*100/preValue)];
    }
    
    return [NSString stringWithFormat:FORMAT_CHANGED_LABEL,
            sign,
            [self stringCurrencyForInteger:(int)diff],
            fabs(diff*100/preValue)];
}

+ (UILabel*)createLabelWithFont:(UIFont*)font textColor:(UIColor *)textColor
{
    UILabel *label = [[UILabel alloc]init];
    label.textColor = textColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = font;    
    label.backgroundColor = [UIColor clearColor];
    
    return label;
}

+ (id)getObject:(NSArray*)objects atIndex:(NSInteger)index
{
    if (objects == nil)
    {
        return nil;
    }
    
    if (index < 0 || [objects count] <= index)
    {
        return nil;
    }
    
    return [objects objectAtIndex:index];
}

+ (NSString*)getDateFromString:(NSString*)strDate inputFormat:(NSString*)inputFormat outputFormat:(NSString*)outputFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:inputFormat];
    NSDate *dateObj = [dateFormatter dateFromString:strDate];
    
    [dateFormatter setDateFormat:outputFormat];
    
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    return [dateFormatter stringFromDate:dateObj];
}

+ (float)convertStringToFloat:(NSString *)value
{
    return [[value stringByReplacingOccurrencesOfString:@"." withString:@""] floatValue];
}

+ (BOOL)isDate:(NSDate*)date1 ssGreaterOrEqualDate:(NSDate*)date2
{
    NSComparisonResult result = [date1 compareWithoutSecondWithDate:date2];
    
    if (result == NSOrderedSame || result ==NSOrderedDescending)
    {
        return YES;
    }
    
    return NO;
}

+ (BOOL)isEmptyString:(NSString *)text
{
    return (text == nil || text.length == 0);
}

+ (NSString *)standardizeRateValue:(NSString *)rateValue
{
    if ([Utility isEmptyString:rateValue] || [rateValue isEqualToString:DEFAULT_EMPTY_OR_ZERO_TEXT]) {
        return @"";
    }
    
    return rateValue;
}

+ (void)openRateApp
{
    NSURL *url;
    
    if (IS_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_IOS7)
    {
        url = [NSURL URLWithString:iOS7AppStoreURLFormat];
    }
    else
    {
        url = [NSURL URLWithString:iOS6AppStoreURLFormat];
    }
    
    [[UIApplication sharedApplication] openURL:url];
}

@end
